package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.hosp.repository.HospitalRepository;
import com.atguigu.yygh.hosp.service.HospitalService;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.vo.hosp.HospitalQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * @author wans
 * @create 2021-11-17 19:48
 */
@Service
public class HospitalServiceImpl implements HospitalService {
    @Autowired
    HospitalRepository repository;

    @Override
    public void save(Map<String, Object> paramMap) {
        //Map类型转换为Hospital对象
        String jsonStr = JSONObject.toJSONString(paramMap);
        Hospital hospital = JSONObject.parseObject(jsonStr, Hospital.class);
        //数据是否存在
        String hoscode = hospital.getHoscode();
        Hospital exist = repository.getHospitalByHoscode(hoscode);
        //存在，对原有医院进行修改
        if (exist != null) {
            hospital.setStatus(exist.getStatus());
            hospital.setIsDeleted(exist.getIsDeleted());
            hospital.setCreateTime(exist.getCreateTime());
            hospital.setUpdateTime(new Date());
        } else {//添加新的医院
            hospital.setStatus(0);
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            repository.save(hospital);
        }


    }

    @Override
    public Hospital getByHoscode(String hoscode) {
        Hospital hospital = repository.getHospitalByHoscode(hoscode);
        return hospital;
    }

    @Override
    public Page selectHospPage(Integer page, Integer limit, HospitalQueryVo vo) {
        //0为第一页
        Pageable pageable = PageRequest.of(page - 1, limit);

        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(vo, hospital);

        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写

        //创建实例
        Example<Hospital> example = Example.of(hospital, matcher);
        Page<Hospital> pages = repository.findAll(example, pageable);

        return pages;

    }
}
